/**
 * Created by Apple on 2016/7/14.
 */
'use strict';

import  SocketIO from 'socket.io-client';
import  Config from './config.js';
import  Define from './define.js';


export  default new class SocketIOHelper {


    //构造方法
    constructor() {
        this.socketIO = null;       //是否链接
        this.isConn = false;        //是否链接

        this.eventCallbackMap = {}; // 事件名做 key, 回调对象  map做value, 每个回调对象包含一个 msgID,  跟callback, msgID做key

        this.connect();
    }


    connect() {
        this.socketIO = SocketIO(Config.socketUrl + ":" + Config.socketPort + Config.socketNamespace);

        var self = this;
        //链接事件
        this.socketIO.on("connect", function (data) {
            console.log("连接成功");
            self.isConn = true;
        });
        //断开事件
        this.socketIO.on("disconnect", function () {
            console.log("断开连接");
            self.isConn = false;
        });
        //错误消息
        // this.socketIO.on("error", function (error) {
        //     console.log(error);
        // });
        // //链接超时
        // this.socketIO.on("connect_timeout", function () {
        //     console.log("链接超时");
        // });
        // //链接错误
        // this.socketIO.on("connect_error", function () {
        //     console.log("链接错误");
        // });
        //
        // this.socketIO.on("reconnect", function (num) {
        //     console.log("重连次数" + num);
        // });
        // this.socketIO.on("ping", function () {
        //     console.log("ping");
        // });
        // this.socketIO.on("pong", function (num) {
        //     console.log("pong" + num);
        // });

        this.registerEvent();
    }

    /**
     * 注册事件
     */
    registerEvent() {
        var self = this;
        for (var key in Define) {

            this.socketIO.on(Define[key], (function (eventName) {
                return function (data) {

                    // console.log({type: "on", data: data});
                    if (data && data.msgID) {
                        var callback = self.eventCallbackMap[eventName][data.msgID];
                        callback && callback(data);
                        //删除掉
                        delete self.eventCallbackMap[eventName][data.msgID];
                    }
                }
            })(Define[key]));

            this.eventCallbackMap[Define[key]] = {};
        }
    }

    /**
     * 监听事件
     */
    listenEvent(event, msgID, callback) {
        if (this.eventCallbackMap[event] && msgID) {
            this.eventCallbackMap[event][msgID] = callback;
        }
        else {
            console.log("监听事件" + event + "或msgID为空");
        }
    }

    /**
     * 发送事件， 返回msgID, 根据这个msgID去注册事件监听
     * @param event
     * @param data
     */
    sendMessage(event, data) {

        var msgID = global.getMsgID();

        this.socketIO.emit(event, {msgID: msgID, data: data});
        return msgID;
    }

}